import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
	namespaced: true,
	state: {
		userList: [],
		user:{},
		count:''
	},
	mutations: {
	 getAlluser(state, {prod,us}) {
			state.userList=prod;
			state.user=us;
			state.count=us.count;
		},
	 getUser(state,data){
		
		  state.user=data
		  console.log(state.user);	 
	 },
	reduceCount(state,data){
		// state.count=state.user.count
		console.log(state.count);
		console.log(data);
		if(parseInt(state.count )  < parseInt(data)){
			alert("积分不足,请进行充值")
		}else {
			state.count-=data;
		}
		 }
	},
	actions: {
		async getAlluser({commit}) {
			try {
				const res = await axios.get("/user/selectAll");
				// console.log(res);
				var us ={}
				var count=''
				const prod = res.data

				var username= localStorage.getItem("username");
				for(var i=0;i<prod.length;i++){
					if(prod[i].username===username){
				   		us=prod[i]
						count=us.count
					}			
				}
				// console.log(us);
		
				commit('getAlluser', {prod,us})
			} catch (e) {
				//TODO handle the exception
				console.log(e);
			}

		},
		async getUser({commit}){
			try {
				const res = await axios.get("/user/selectOne?id=1");
				console.log(res);
				var us ={}
				const prod = res.data
				console.log(prod);
				var username= localStorage.getItem("username");
				for(var i=0;i<prod.length;i++){
					if(prod[i].username===username){
				   		us=prod[i]
					}			
				}
				commit('getUser',prod)
			} catch (e) {
				//TODO handle the exception
				console.log(e);
			}
		},
		
		async addCount({commit,state},item){
			
		},
		async reduceCount({commit,state},item){
			// console.log(state.user);
			// console.log(item);
			commit('reduceCount',item);
		}
		
	}

})
